/*
 * Copyrignt (c) doubimeizhi.com. All Rights Reserved.
 * Author: mr.gao<fbg@live.com>
 * Created Time: 2017-02-16 15:06
 * Last Modified: 2017-07-28 14:32:37
 * File Name: qkcoupon/controllers/receive_coupon.go
 * Description:
 */

package controllers

import (
	"encoding/json"
	"qkcoupon/cache"
	"qkcoupon/db"
	"qkcoupon/errorcode"
	"qkcoupon/models"
	"qkcoupon/rpc/client/passport"
	"time"

	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

type ReceiveRecommendController struct {
	URLSignController
}

/*
 *@note  验证请求参数
 *@return uint: 错误码
 */
func (p *ReceiveRecommendController) verification(req *models.PCQkCouponReceiveRecommendReq) uint {
	var errCode uint = errorcode.EC_GL_SUCCESS

	for {
		//验证新手机号
		if !utility.ValidateMobile(req.Mobile) {
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		var up *models.PQSQkCouponUserProfile
		up, _ = passport.GetUserProfileByAccount(req.Mobile)
		//errCode老是返回code:503001 msg:"internal server error"
		//需要叫账户系统改
		//if errCode != errorcode.EC_GL_SUCCESS {
		//	break
		//}
		if up == nil {
			up = &models.PQSQkCouponUserProfile{}
		}

		//推荐者不能等于接收者
		if up.UserId == req.RecommendId {
			errCode = errorcode.EC_QKCOUPON_CANT_RECOMMEND_MYSELF
			break
		}

		//已经是老用户
		if up.UserId != "" {
			errCode = errorcode.EC_QKCOUPON_ALREADY_OLD_USER
			break
		}

		break
	}

	return errCode
}

func (p *ReceiveRecommendController) userInfoEx2ReceiveRecommendRsp(mobile string, uie *models.PSQkCouponUserInfoEx) *models.PCQkCouponReceiveRecommendRsp {
	rr := &models.PCQkCouponReceiveRecommend{}
	rr.Name = mobile
	rr.Ctype = uie.BaseInfo.Ctype
	rr.Lmode = uie.BaseInfo.Lmode
	rr.Sum = uie.BaseInfo.Sum
	rr.Discount = uie.BaseInfo.Discount

	rsp := &models.PCQkCouponReceiveRecommendRsp{}
	rsp.List = append(rsp.List, rr)

	return rsp
}

func (p *ReceiveRecommendController) createRecommendCoupon(req *models.PCQkCouponReceiveRecommendReq) (int64, uint) {
	ccr := &models.PSQkCouponCreateCouponReq{}
	ccr.Sum = 2000
	ccr.Discount = 900
	ccr.MaxDiscount = 0
	ccr.Ctype = 2
	ccr.Lmode = 0
	ccr.Utype = 2

	var timeLayout = "2006.01.02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	curTick := time.Now().Unix()

	startDate := time.Unix(curTick, 0).Format("2006.01.02")
	startTime := "00:00:00"
	timeStr := startDate + " " + startTime
	tmpTick, _ := time.ParseInLocation(timeLayout, timeStr, loc)
	startTick := tmpTick.Unix()

	endDate := time.Unix(curTick+int64(4*models.DAY_UNIT), 0).Format("2006.01.02")
	endTime := "23:59:59"
	timeStr = endDate + " " + endTime
	tmpTick, _ = time.ParseInLocation(timeLayout, timeStr, loc)
	endTick := tmpTick.Unix()

	timeRanges := &models.PCQkCouponTimeRanges{}
	timeRanges.Date = make([]*models.PCQkCouponDataRange, 0)
	timeRanges.Date = append(timeRanges.Date, &models.PCQkCouponDataRange{Start: startDate, End: endDate})
	timeRanges.Time = make([]*models.PCQkCouponDataRange, 0)
	timeRanges.Time = append(timeRanges.Time, &models.PCQkCouponDataRange{Start: startTime, End: endTime})
	ccr.TimeRanges = timeRanges

	cid, errCode := db.CreateCoupon(ccr, startTick, endTick, 0)
	if errCode != errorcode.EC_GL_SUCCESS {
		return 0, errCode
	}

	return cid, errorcode.EC_GL_SUCCESS
}

// @router /receive [post]
func (p *ReceiveRecommendController) ReceiveRecommend() {
	defer p.Output("ReceiveRecommend")

	data := p.Ctx.Input.RequestBody
	if len(data) == 0 {
		log.Warn("len(data)==0")
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	log.Debug(string(data))

	req := &models.PCQkCouponReceiveRecommendReq{}
	err := json.Unmarshal(data, req)
	if err != nil {
		log.Warn(err.Error())
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	obj := cache.GetReceiveRecommendCount()
	count := obj.Get(req.RecommendId, p.Ctx.Input.IP())
	if count > 100 {
		log.Warn(errorcode.Msg(errorcode.EC_QKCOUPON_BIND_PEOPLE_OVER_RANGE))
		p.Resp["code"] = errorcode.EC_QKCOUPON_BIND_PEOPLE_OVER_RANGE
		return
	}

	errCode := p.verification(req)
	if errCode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errCode
		return
	}

	errCode = db.IsExistRecommendInfo(req.RecommendId)
	if errCode == errorcode.EC_QKCOUPON_RECOMMEND_NOT_EXIST {
		p.Resp["code"] = errCode
		return
	}

	ccode, errCode := db.IsReceiveRecommendCoupon(req.Mobile)
	if errCode != errorcode.EC_GL_SUCCESS {
		if errCode == errorcode.EC_QKCOUPON_ALREADY_RECEIVE_RECOMMEND {
			recommendId, _ := db.GetRecommender(req.Mobile)
			//如果推荐者不一样，则更新为新的推荐者
			if recommendId != req.RecommendId {
				_, errCode = db.UpdateRecommendRecommendId(req.RecommendId, req.Mobile)
				if errCode != errorcode.EC_GL_SUCCESS {
					p.Resp["code"] = errCode
					return
				}

				p.Resp["code"] = errorcode.EC_GL_SUCCESS
			} else {
				p.Resp["code"] = errorcode.EC_QKCOUPON_ALREADY_RECEIVE_RECOMMEND
			}
		} else {
			p.Resp["code"] = errCode
			return
		}
	} else {
		ccode, errCode = db.ReceiveRecommend(req.RecommendId, req.Mobile, models.EQKCOUPON_OPERATOR_RECEIVER)
		if errCode != errorcode.EC_GL_SUCCESS {
			p.Resp["code"] = errCode
			return
		}

		p.Resp["code"] = errorcode.EC_GL_SUCCESS
	}

	if p.Resp["code"] == errorcode.EC_GL_SUCCESS {
		obj.Increase(req.RecommendId, p.Ctx.Input.IP())
	}

	uie, errCode := db.GetCoupon("", req.Mobile, ccode)
	if errCode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errCode
		return
	}

	log.Debugf("PSQkCouponUserInfoEx:%v", uie)

	p.Resp["data"] = p.userInfoEx2ReceiveRecommendRsp(req.Mobile, uie)
}
